<?php
/*
---------------------------------------------------------
														+
名称:易通支付通道										+
														+
控制器名称:YiTongController								+
														+
日期:2017-10-11											+
														+
作者:小翁												+
														+
---------------------------------------------------------
*/
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

class MaikouController extends PayController{
    protected $config;
    protected $key;
    protected $url;
    protected $class;

    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));

    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);
        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $return = $this->orderadd( $parameter );

        switch($this->config['paytype']){
            //银联快捷
            case 13:
                $pay_bankcode = 'BC_EXPRESS';
                break;
            default:
                $this->showmessage('不支持此产品!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        // 构造要请求的参数数组
        $parameter = array(
            "app_id" => $this->config['mch_id'],
            "timestamp" => strval(getMillisecond()),
            "channel" => $pay_bankcode,
            "total_fee" => intval($return['amount']*100),
            "bill_no" => $return['orderid'],
            "title" => '0',
            "notify_url" => $return['notifyurl'],
            "return_url" => $return['callbackurl'],

        );

        $parameter["app_sign"] =  md5($parameter['app_id'].$parameter['timestamp'].$this->config['signkey']);
        $res = curl($this->config['gateway'], httpstr($parameter));//curl_post
        $resp = json_decode($res,true);

        if($resp['result_code'] === 0){
            header("Location: {$resp['url']}");
        }

        if($resp['result_msg']){
            $this->showmessage($res['result_msg'], ['code' => C("THIRDCODES." . $this->class)]);
        }
        $this->showmessage('未获取到支付链接!',['code'=>C("THIRDCODES.".$this->class)]);
    }



    //通知
    public function notifyurl(){
        //$this->debug_callback();

        if(!$this->checkip(getIP(),['47.112.96.93'])){
            exit("wrong");
        }

        $p = file_get_contents("php://input");
        $p = json_decode($p,true);

        /*
{"bill_fee":100,"discount":0,"channelType":"BC","buyer_id":"","channel_transaction_id":"631904301953566842618","partition_id":"","coupon_id":"","tradeSuccess":true,"id":"61b03151-db60-45b0-b9bf-f0c737d609ae","channel_type":"BC","app_id":"fea967c1-fecf-4227-ad78-98fc432d8107","retryCounter":2,"transaction_id":"2019043019520781051","retry_counter":0,"transaction_fee":100,"sub_channel_type":"BC_EXPRESS","optional":[],"is_recharge_consume":false,"transaction_type":"PAY","notify_url":"http://api.abelpurse.com/pay/bike/order_callback/index","transactionId":"2019043019520781051","transactionType":"PAY","transactionFee":100,"recharge_user":"","notifyUrl":"http://api.abelpurse.com/pay/bike/order_callback/index","messageDetail":{"currencyType":"156","tranDateTime":"20190430195203","respMessage":"交易成功","serviceCode":"unionpay.wappay","sign":"XqNniZV8j7TpUHX96vvOYhm3PfV251PgNZvcaDa4Mjm80M3sIOoxk9Tubt3NtMCotVy+bFnq2O5G8qNBtdwbB+pbCSBFLCD8GjTBw5mwYpFTd5ukEO2pLEY3L6LclOHEYeHosUanc8SPCyLKqFu7yR0bF0WTQg7mnIsZQEnxrTWhu+d11gTQaYwKwoYisqZ+tJMoRqg5p5kgPMeqowgCS3tCV1kRKYex/Fq5uI7hvKIw2PkkIB/nTxHhslVbdfoMiAbpgtDpuwNrbyLLlraN1wcjFzrVbBVQ/MSVY7vbQsvTyU6xCb2ToeCPiGW8/A0Lv8SbYLdM+dlUtRJVsjtokA==","version":"20171201","merOrderNum":"2019043019520781051","tranRefNum":"PY1904301952042085","transactionFee":100,"merchantId":"910190305101696","tradeSuccess":true,"outTransactionId":"631904301953566842618","tranAmt":"100","acctType":"00","tranCode":"1000","respCode":"0000"},"message_detail":{"currencyType":"156","tranDateTime":"20190430195203","respMessage":"交易成功","serviceCode":"unionpay.wappay","sign":"XqNniZV8j7TpUHX96vvOYhm3PfV251PgNZvcaDa4Mjm80M3sIOoxk9Tubt3NtMCotVy+bFnq2O5G8qNBtdwbB+pbCSBFLCD8GjTBw5mwYpFTd5ukEO2pLEY3L6LclOHEYeHosUanc8SPCyLKqFu7yR0bF0WTQg7mnIsZQEnxrTWhu+d11gTQaYwKwoYisqZ+tJMoRqg5p5kgPMeqowgCS3tCV1kRKYex/Fq5uI7hvKIw2PkkIB/nTxHhslVbdfoMiAbpgtDpuwNrbyLLlraN1wcjFzrVbBVQ/MSVY7vbQsvTyU6xCb2ToeCPiGW8/A0Lv8SbYLdM+dlUtRJVsjtokA==","version":"20171201","merOrderNum":"2019043019520781051","tranRefNum":"PY1904301952042085","transactionFee":100,"merchantId":"910190305101696","tradeSuccess":true,"outTransactionId":"631904301953566842618","tranAmt":"100","acctType":"00","tranCode":"1000","respCode":"0000"},"is_recharge":false,"trade_success":true,"partition_info":"","signature":"4f5e90f5940597bd218e47e0f2372c23","sign":"044c10effb1af9d497a2bdd23ac4f683","signAll":"5898692f21ef88bdfd1c2a6cd0269e27","timestamp":1556625300000}
         * */

            //获取订单信息
        $orderid = $p['transaction_id'];
        $find = $this->checkOrderNotify($orderid);

        if(!$find){
            echo 'order_not_found'; exit;
        }
        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$orderid))->save(array(

            "pay_orderid_rd"=>htmlspecialchars($p['channel_transaction_id'])));

        //获取渠道信息
        $this->config = M("Channel")->where(array('code'=>$this->class))->find();

        $sign = $p['signature'];

        //app_id + transaction_id + transaction_type + channel_type + transaction_fee + master_secret
        $sign1 = md5($p['app_id'].$p['transaction_id'].$p['transaction_type'].$p['channel_type'].$p['transaction_fee'].$this->config['appid']);


        if($sign1 !== $sign ){
            exit("sign_wrong");
        }

        if($p['trade_success'] !== true){
            exit("pay_fail");
        }

        $this->async($find['pay_orderid'],'success');
    }

    public function callBackUrl(){

        echo '支付成功'; exit;
    }
}